<?php

class RoomWorker extends Worker{
	/**
	 * roomGrade
	 */
	public function roomList(){
            $runData = $this->getRunData();
            $grade = 0;
            if( isset($runData['roomGrade']) )
                $grade = intval($runData['roomGrade']);
            
            $model = $this->loadModel('Room');
            $data = array();
            $roomArr = $model->getAllByWhere(" roomGrade = '{$grade}' AND isDel = '0' ");
            foreach( $roomArr AS $v ){
                $newarray = array();
                $newarray['roomID']     = $v['id'];
                $newarray['title']      = $v['title'];
                $newarray['roomGrade']  = $v['roomGrade'];
                $newarray['addExp']     = $v['addExp'];
                $newarray['lBlind']     = $v['lBlind'];
                $newarray['bBlind']     = $v['bBlind'];
                $newarray['lGameMoney'] = $v['lGameMoney'];
                $newarray['BGameMoney'] = $v['BGameMoney'];
                $newarray['DeskMaxHuman'] = $v['DeskMaxHuman'];
                $newarray['gameSpeed']  = $v['gameSpeed'];
                $newarray['condition']  = unserialize($v['condition']);
                $newarray['nowHuman']   = $this->getRoomHuman($v['id']);
                $data[] = $newarray;
            }
            if( 0 < count($data) ){
                $this->socketWrite(array('code'=>1,'data'=>$data));return;
            }else{
                $this->socketWrite(array('code'=>1,'data'=>'no rooms'));return;
            }
	}
        
        private function getRoomHuman( $roomID ){
            $human = 0;
            $model = $this->loadModel('Room');
            $sql = " SELECT userInfo FROM pk_game WHERE roomID = '{$roomID}' ";
            $data = $model->getRow($sql);
            if($data['userInfo']){
                $userArr = unserialize( $data['userInfo'] );
                $human = count($userArr);
            }
            return $human;
        } 
        
        /*进入房间*/
	public function enterRoom(){
            $runData = $this->getRunData();
            $userID = $runData['userID'];
            $roomID = $runData['roomID'];
            $userData = array();
            $model = $this->loadModel('Game');
            
            /*获取房间内所有观战的用户*/
            $model = $this->loadModel('Game');
            /*取出游戏房间的所有用户信息*/            
            $gameInfo = $model->getGameInfo(array("roomID"=>$roomID));
            if(!$gameInfo){
            	$this->socketWrite(array('code'=>0,'data'=>'房间不存在'));return;
            }
            $userData = $gameInfo['lookInfo'];
            if( isset($userData[$userID]) ){
                $this->socketWrite(array('code'=>0,'data'=>'already in'));return;
            }
            foreach($gameInfo['userInfo'] as $user){
            	if($user['userID'] == $userID){
            		$this->socketWrite(array('code'=>0,'data'=>'already in'));return;
            	}
            }	
            //$userData[$userID] = $userID;
            $gameInfo['lookInfo'][$userID] = $userID;
            $model->saveGame($gameInfo);
            $newUserInfo = pkReturnUserInfo($gameInfo['userInfo'],$runData['roomID']);
            if(!$newUserInfo){
            	$this->socketWrite(array('code'=>0,'data'=>'获取房间信息失败'));return;
            }
            $gameInfo['userInfo'] = $newUserInfo;
            if($gameInfo['status'] < 3){ //未发公共牌
            	$gameInfo['pk'] = array();
            }
            $this->socketWrite(array('code'=>1,'data'=>$gameInfo));return;
            
	}
        
        /*进入座位*/
	public function sitDown(){
            $runData = $this->getRunData();           
            if(!isset($runData['userID'],$runData['roomID'],$runData['seat'],$runData['jetton'])){
            	$this->socketWrite(array('code'=>0,'data'=>'parameter error'));return;            
            }
            $userID = $runData['userID']; //用户id
            $roomID = $runData['roomID']; //房间id
            $seat   = $runData['seat']?$runData['seat']:0;   //座位号
            $jetton = $runData['jetton']; //筹码数
            $userData = array();
            
            /*取出游戏房间的所有用户信息*/  
            $model = $this->loadModel('Game');
            $gameInfo = $model->getGameInfo(array("roomID"=>$roomID));
            if(!$gameInfo){
            	$this->socketWrite(array('code'=>0,'data'=>'房间不存在'));return;
            }            
            /*取出用户信息*/
            $usersql = " SELECT * FROM pk_user_info WHERE userID = '{$userID}'";
            $zxUser = $model->getRow($usersql);
            /*取出房间的基础信息*/
            $roomsql = " SELECT DeskMaxHuman FROM pk_room WHERE id = '{$roomID}' LIMIT 1 ";
            $room = $model->getRow($roomsql);
            $userData = $gameInfo['userInfo'];
            $userLook = $gameInfo['lookInfo'];
            //验证是否可以座
            if( $seat > $room['DeskMaxHuman']-1 ){
            	$this->socketWrite(array('code'=>0,'data'=>'座位不存在'));return;
            }            
            if(isset($userData[$seat])){
            	$this->socketWrite(array('code'=>0,'data'=>'该座位已有用户'));return;
            }
            foreach($userData as $user){
            	if($user['userID'] == $userID){
            		$this->socketWrite(array('code'=>0,'data'=>'already in site'));return;
            	}
            }
            //print_r($gameInfo);exit;
            //exit;
           
            /*拼接用户信息*/
            $arr = $this->config->getKey("gameUserInfoTemp")->get();
            $arr['userID']      = $userID; //用户id
            $arr['userName']    = $zxUser['userName']?$zxUser['userName']:'player'; //用户名
            $arr['avatar']      = $zxUser['avatar']?$zxUser['avatar']:''; //用户头像
            $arr['time']        = time();    //进入房间时间
            $arr['jetton']      = $jetton; //手中筹码数
            $arr['seat']        = $seat;    //座位号
            /*插入用户信息到桌子上，键值为座位号*/
            $gameInfo['userInfo'][$seat] = $arr;                 

            /*把用户信息从观看栏里清除*/
            if(isset($gameInfo['lookInfo'][$userID]))
                unset($gameInfo['lookInfo'][$userID]);
            $gameInfo['lookInfo'] = empty($gameInfo['lookInfo'])?'':$gameInfo['lookInfo'];
            /*设置默认庄主*/
            if( 1 == count( $gameInfo['userInfo'] ) ){
                $gameInfo['banker'] = $seat;
            }
            
            $model->saveGame($gameInfo);
            
            /*减掉用户手里的筹码数*/
            $usermoney = $this->loadModel('UserInfo');
            $usermoney->minJetton( $jetton , $userID );		
           
            $this->socketWrite(array('code'=>1,'data'=>array('seat'=>$seat)));return;
	}
    
        /*离开房间*/
        public function leaveRoom(){
            $runData = $this->getRunData();
            $userID = $runData['userID'];
            $roomID = $runData['roomID'];
            $seat   = isset($runData['seat'])?$runData['seat']:-1;   //座位号            
            $model = $this->loadModel('Game');
            $gameInfo = $model->getGameInfo(array("roomID"=>$roomID));
            if(!$gameInfo){
            	$this->socketWrite(array('code'=>0,'data'=>'房间不存在'));return;
            }    
            $playing = $gameInfo['userInfo'];
            $looking = $gameInfo['lookInfo'];
            /*
             * 从座位号离开房间的时候分2步 
             * 1.把剩余的筹码添加进用户的信息表
             * 2.清空游戏中的用户信息
             */
            if( -1 != $seat ){
                $user = $this->loadModel('UserInfo');
                $user->plusJetton( $playing[$seat]['jetton'] , $userID );
                unset($playing[$seat]);
                if( 0 < count($playing) ){
                    $set['userInfo'] = serialize($playing);
                }else{
                    $set['userInfo'] = '';
                }
                if( $gameInfo['banker'] == $runData['seat'] ){
                    $set['banker'] = $this->nextSeat( $playing , $seat);
                }   
            }else{
                /*直接离开房间*/
                unset($looking[$userID]);
                if( 0 < count($looking) ){
                    $set['lookInfo'] = serialize($looking);
                }else{
                    $set['lookInfo'] = '';
                }
            }
            $where = 'WHERE roomID = '.$roomID;
            $model->update($set , $where);;
            $this->socketWrite(array('code'=>1,'data'=>'success'));return;
            
        } 
        
	/**
	 * 返回下当前座位号的下一个玩家座位
	 * @param unknown_type $userInfo
	 * @param unknown_type $preBaner
	 * @return unknown|Ambigous <number, unknown>
	 */
	protected function nextSeat($userInfo,$Seat){
		//$maxUserNum = 5;//房间最大人数
		$maxSeat = -1;
		foreach ($userInfo as $skey=>$user){
			if($skey > $maxSeat){
				$maxSeat = $skey;
			}
		}
		$Seat = $Seat>=$maxSeat?-1:$Seat;
		foreach ($userInfo as $skey=>$user){
			if($skey > $Seat){
				return $skey;break;
			}
		}
		return $Seat;
	}
}